package com.hts.utils.file;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @author hs
 * @version 1.0
 * @date: 2023/4/11
 */
public class ZipUtils {
    public static ByteArrayOutputStream zip(Map<String, InputStream> map) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
        try {
            map.forEach((k, v) -> {
                try {
                    zipOutputStream.putNextEntry(new ZipEntry(k));
                    write(v, zipOutputStream);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        } finally {
            zipOutputStream.close();
        }
        return byteArrayOutputStream;
    }

    public static void write(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, length);
        }
//        outputStream.close();
//        inputStream.close();
    }
    /**
     * 修改文件内容
     *
     * @param inputStream  输入zip 流
     * @param outputStream 输出zip 流
     * @param isUpdate     修改条件
     * @param handle       修改的具体逻辑处理
     * @throws IOException
     */
    public static void updateZipContent(InputStream inputStream, OutputStream outputStream, Predicate<ZipEntry> isUpdate, Function<byte[], byte[]> handle) throws IOException {
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry nextEntry = zipInputStream.getNextEntry();
        while (nextEntry != null) {
            if (isUpdate.test(nextEntry)) {
                byte[] bytes = zipInputStream.readAllBytes();
                byte[] apply = handle.apply(bytes);
                zipOutputStream.putNextEntry(new ZipEntry(nextEntry.getName()));
                zipOutputStream.write(apply);

            } else {
                //不是的也需要解压
                zipOutputStream.putNextEntry(new ZipEntry(nextEntry.getName()));
                byte[] buf = new byte[1024];
                int len;
                while ((len = zipInputStream.read(buf)) > 0) {
                    zipOutputStream.write(buf, 0, len);
                }
            }
            nextEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.close();
        inputStream.close();
        zipOutputStream.close();
    }
}
